package com.gzdh.tang.modu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.mapper.ReserveMapper;
import com.gzdh.tang.modu.mapper.ReserveXfjTempMapper;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.modu.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DS("card")
@Slf4j
@Service("reserveServiceXfjTemp")
public class ReserveXfjTempServiceImpl extends ServiceImpl<ReserveXfjTempMapper, ReserveXfjTemp> implements ReserveXfjTempService {
    @Autowired
    FkService fkService;

    @Autowired
    GsService gsService;

    @Autowired
    MacMainpSbruanService macMainpSbruanService;

    @Autowired
    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    @Autowired
    MacMainpSbruanKlService macMainpSbruanKlService;

    @Override
    public Map<String, Object> toCardPay2(String deviceId, int price, Fk fk, String reqSeqNo, int type, Date date, JSONObject priceRule) throws RuntimeException {
        Map<String, Object> resMap = new HashMap<>();
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
        BigDecimal xfPrice2 = new BigDecimal(price).divide(new BigDecimal(100));
        BigDecimal xfPrice3 = new BigDecimal(0);
        if (price == 0) {
            throw new RuntimeException("金额异常，请重新输入");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService
                .list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId, macMainpSbruan.getId()));
        if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
            throw new RuntimeException("不支持此卡类");
        }
        String sc = "0";
        BigDecimal cardPrice = new BigDecimal(0);
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        if (btye.compareTo(new BigDecimal(0)) > 0) {
            sc = "1";
            cardPrice = btye;
            if (btye.compareTo(xfPrice2) <= 0) {
                xfPrice = btye;
                fk.setBtye("0");
            } else {
                fk.setBtye(btye.subtract(xfPrice2).toPlainString());
            }
            xfPrice3 = xfPrice3.add(xfPrice);
        } else if (kye.compareTo(new BigDecimal(0)) > 0) {
            sc = "0";
            cardPrice = kye;
            if (kye.compareTo(xfPrice2) <= 0) {
                //卡余额小于消费，需要扣支付宝金额
                xfPrice = kye;
            }
            fk.setKye(kye.subtract(xfPrice2).toPlainString());
            xfPrice3 = xfPrice3.add(xfPrice);
        } else {
            sc = "4";
        }

//        if (xfPrice3.subtract(xfPrice).compareTo(new BigDecimal(0)) <= 0) {
//            resMap.put("fk", fk);
//            resMap.put("amount", xfPrice3);
//            return resMap;
//        }
        int counts = this.count(new QueryWrapper<ReserveXfjTemp>().lambda()
                .eq(ReserveXfjTemp::getLsh2, String.valueOf(reqSeqNo))
                .eq(ReserveXfjTemp::getPosnum, macMainpSbruan.getPos()));
        if (counts == 0) {
            insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan,
                    "现金菜", macMainpSbruan.getCode(), cardPrice, sc, String.valueOf(reqSeqNo), date, priceRule);
        }
        xfPrice = xfPrice2.subtract(xfPrice3);
        if ("1".equals(sc) && xfPrice.compareTo(new BigDecimal(0)) > 0) {
            //上一笔为补贴的操作，继续计算自购剩余金额
            sc = "0";
            cardPrice = kye;
            date = new Date(date.getTime() + 100);
            //上一笔扣补贴，并存在没扣完;
            if (kye.compareTo(xfPrice) <= 0) {
                //卡余额小于消费，需要扣支付宝金额
                xfPrice = kye;
            }
            xfPrice3 = xfPrice3.add(xfPrice);
            insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(),
                    1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(), cardPrice, sc, String.valueOf(reqSeqNo), date, priceRule);
            fk.setKye(kye.subtract(xfPrice).toPlainString());
            xfPrice = xfPrice2.subtract(xfPrice3);
        }
        if (xfPrice.compareTo(new BigDecimal(0)) > 0 && ("0".equals(sc) || "1".equals(sc))) {
            //自购和补贴都计算完后需要支付宝计算金额
            date = new Date(date.getTime() + 100);
            insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(),
                    1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(), cardPrice, "4", String.valueOf(reqSeqNo), date, priceRule);
        }
        resMap.put("fk", fk);
        resMap.put("amount", xfPrice3);
        return resMap;
    }

    @Override
    public boolean insertReserve(String rgTermSN, String reqSeqNo, int price, int sl, Fk fk,
                                 MacMainpSbruan macMainpSbruan, String hName, String code,
                                 BigDecimal cardPrice, String sc, String orders, Date date, JSONObject priceRule) throws RuntimeException {
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
        BigDecimal yePrice = new BigDecimal(0);
        String je = (new BigDecimal(price).multiply(new BigDecimal(sl))).divide(new BigDecimal(100)).toPlainString();
        yePrice = cardPrice.subtract(xfPrice);
        ReserveXfjTemp reserve = new ReserveXfjTemp();
        reserve.setZkl("100");
        reserve.setCardno(fk.getCardno());
        reserve.setZl(macMainpSbruan.getZl());
        reserve.setBqh(macMainpSbruan.getBqh());
        reserve.setKsh(macMainpSbruan.getKsh());
        reserve.setBed("0");
        reserve.setPosnum(macMainpSbruan.getPos());
        reserve.setDinner(macMainpSbruan.getDinner());
        reserve.setCode(code);
        reserve.setSl(sl);
        reserve.setStatus("1");
        reserve.setJe(je);
        reserve.setOriginalAmount(je);
        reserve.setDiscountAmount("0");
        if (priceRule != null) {
            reserve.setDiscountAmount(priceRule.getString("yPrice"));
            reserve.setOriginalAmount(priceRule.getString("price"));
        }
        try {
            reserve.setYe(yePrice.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
        } catch (Exception e) {
            log.error("余额错误");
            reserve.setYe("0");
        }
        reserve.setKl(fk.getKl());
        reserve.setSc(sc);
        reserve.setLsh2(String.valueOf(reqSeqNo));
        reserve.setCzrq(date);
        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        reserve.setHname(hName);
        reserve.setSddz(rgTermSN);
        reserve.setCs(0);
        reserve.setOpenid(fk.getCardsn());
        reserve.setKehu(fk.getName());
        reserve.setZfserialnumber(orders);
        reserve.setAddr(macMainpSbruan.getAddr());
        this.save(reserve);
        return true;
    }

    private String getDinner(MacMainpSbruan macMainpSbruan) throws Exception {
        String hourMin = new SimpleDateFormat("HH:mm").format(new Date());
        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService
                .list(new QueryWrapper<MacMainpSbruanDinner>().lambda().eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
            if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                return goo.getDinner();
            }
        }
        throw new Exception("未找到该灶类");
    }

    private boolean judeKl(List<MacMainpSbruanKl> macMainpSbruanKlList, String kl) {
        for (MacMainpSbruanKl goo : macMainpSbruanKlList) {
            if (goo.getKl().equals(kl.trim())) {
                return true;
            }
        }
        return false;
    }

}
